<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Express;
use app\common\model\Cart;
use app\common\model\goods\Goods;
use app\common\model\goods\Spec;
use app\common\model\Invoice;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\Order as OrderOrder;
use app\common\model\User;
use think\Db;
use think\Validate;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @ApiTitle (下单预览)
     * @ApiMethod (POST)
     * @ApiParams (name="ids", type="string", required=true, sample="", description="购物id|商品id")
     * @ApiParams (name="spec_id", type="integer", required=true, sample="", description="规格id（立即购买必填）")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="数量（立即购买必填）")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="1=购物购买，2=立即购买")
     * @ApiParams (name="address_id", type="integer", required=true, sample="", description="地址ID")
     * @ApiParams (name="order_type", type="integer", required=true, sample="", description="1=配送订单,2=自提订单")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function yu_order()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;

        try {
            if ($type == 2) {
                $param = [
                    'num' => $num,
                    'user_id' => $uid,
                    'goods_id' => $ids,
                    'spec_id' => $spec_id,
                ];
                $cart_ids = Cart::add($param, 1, $type);
            } else {
                $cart_ids = $ids;
            }
            $goods = OrderOrder::yuOrder($cart_ids, $uid, $order_type, $address_id??0, $type,$order_class??1);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('', $goods);
    }
    /**
     * 检测体验商品限购
     *
     * @ApiMethod (POST)
     * @param string $id    商品id
     * @param string $num   数量
     */
    public function check_goods()
    {
        $param = request()->param();
        $param['uid'] = $this->auth->id;
        try {
            OrderOrder::check_goods($param);
        } catch (\Exception $e) {
            if ($e->getCode() == 1) {
                $this->error('', $e->getMessage(), 1);
            } else {
                $this->error($e->getMessage());
            }
        }
        $this->success();
    }

    /**
     * @Author LK
     * @ApiTitle (订单下单)
     * @ApiMethod (POST)
     * @ApiParams (name="ids", type="string", required=true, sample="", description="购物id|商品id")
     * @ApiParams (name="spec_id", type="integer", required=true, sample="", description="规格id（立即购买必填）")
     * @ApiParams (name="num", type="integer", required=true, sample="", description="数量（立即购买必填）")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="1=购物购买，2=立即购买")
     * @ApiParams (name="address_id", type="integer", required=true, sample="", description="地址ID")
     * @ApiParams (name="order_type", type="integer", required=true, sample="", description="1=配送订单,2=自提订单")
     * @ApiParams (name="order_class", type="integer", required=true, sample="", description="1=普通订单,2=体验订单,3=积分订单")
     * @ApiParams (name="is_yue", type="integer", required=true, sample="", description="0否  1是")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_order()
    {
        $param = request()->param();
        extract($param);

        $uid = $this->auth->id;
        try {
            if ($type == 2) {
                $param = [
                    'num' => $num,
                    'user_id' => $uid,
                    'goods_id' => $ids,
                    'spec_id' => $spec_id,
                ];
                $cart_ids = Cart::add($param, 1, $type);
            } else {
                $cart_ids = $ids;
            }
            $goods = OrderOrder::yuOrder($cart_ids, $uid,  $order_type, $address_id??0, $type,$order_class??1);
            $orderid = OrderOrder::addOrder($goods, $is_yue, $order_type, $order_class);
            if ($orderid) {
                Cart::whereIn('id', $cart_ids)->where('user_id', $this->auth->id)->delete();
                queue('app\\common\\job\\CancelOrder', $orderid, 900, '1291cancelorder');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('', $orderid);
    }

    /**
     * @Author LK
     * @date: 2023-10-23 
     * @ApiTitle (订单列表)
     * @ApiMethod (GET)
     * @ApiParams (name="order_status", type="string", required=true, sample="", description="all=全部,0=待支付,10=待发货,20=待收货,30=待提货,40=已完成,-1=已取消")
     * @ApiParams (name="order_class", type="string", required=true, sample="", description="1=现金类,2=积分类)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_list()
    {
        $param = request()->param();
        extract($param);
        $order = new OrderOrder();
        if ($order_status != 'all') {
            $order->where('order_status', $order_status);
        }
        if ($order_class == 1) {
            $order->whereIn('order_class', ['1', '2','4']);
        } else {
            $order->where('order_class', '3');
        }
        $lists = $order->with(['goods'])->where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $lists);
    }

    /**
     * @Author LK
     * @date: 2023-10-23 
     * @ApiTitle (订单详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function order_info()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id, ['goods']);
        $this->success('', $order);
    }

    /**
     * @Author LK
     * @date: 2023-10-23 
     * @ApiTitle (取消订单)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function cancel_order()
    {
        $id = request()->param('id');
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id, ['goods']);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->order_status != '0') {
            $this->error('订单不可取消');
        }
        Db::startTrans();
        try {
            $order->order_status = '-1';
            $res = $order->save();
            if ($res) {
                foreach ($order->goods as $k => $v) {
                    Spec::stockUp($v['goods_id'], $v['spec_id'], $v['goods_num']);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('取消成功');
    }

    /**
     * @Author LK
     * @date: 2023-12-14 
     * @ApiTitle (删除订单)
     * @ApiMethod (GET)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function del_order()
    {
        $id = request()->param('id');
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id, ['goods']);
        if (!$order) {
            $this->error('订单不存在');
        }
        if ($order->order_status != '-1') {
            $this->error('订单不可删除');
        }
        try {
            $res = $order->delete();
            if ($res) {
                foreach ($order->goods as $key => $v) {
                    $v->delete();
                }
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('删除成功');
    }
    /**
     * @Author LK
     * @date: 2023-10-23 
     * @ApiTitle (查看物流)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiParams (name="type", type="string", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function logistics()
    {
        $param = request()->param();
        extract($param);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = OrderOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        $express = new Express($order);
        $wuliu = $express->getOrderTracesByJson();
        $wuliu['express_name'] = Db::name('express')->where('customer', $order['express_com'])->value('name');
        $wuliu['address'] = $order['address'];
        // $wuliu['city'] = $order['city'];
        $wuliu['nu'] = $order['express_no'];
        $this->success('', $wuliu);
    }
    /**
     * @Author LK
     * @date: 2023-11-03 
     * @ApiTitle (确认收货)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function confirmOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            OrderOrder::confirmOrder($post);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error('操作失败：' . $th->getMessage());
        }
        $this->success('操作成功');
    }
}
